<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script>
      // -------不安全-----------------------------
      var _unique = null;

      function createSingle() {
        var obj = {
          a: 1,
        };
        if (_unique === null) {
          _unique = obj;
        }
        return _unique;
      }

      var a = createSingle();
      //   _unique = null--不安全
      var b = createSingle();

      console.log(a === b); //true

      // -------安全--------------------------------
      var createSingle2 = (function () {
        var _unique2 = null;
        function single() {
          return {
            a: 1,
          };
        }
        return function () {
          if (_unique2 === null) {
            _unique2 = single();
          }
          return _unique2;
        };
      })();

      var a2 = createSingle2();
      var b2 = createSingle2();
      console.log(a2 === b2); //true
    </script>
  </head>
  <body></body>
</html>
